import React, { useState, useEffect } from 'react'
import "./Password.css"
import { Space } from 'react-vant'
import { Down } from '@react-vant/icons'
import { NumberKeyboard } from '@nutui/nutui-react'
import { PasswordInput, Dialog } from 'react-vant';
import { Button, Toast } from 'antd-mobile'
import { sleep } from 'antd-mobile/es/utils/sleep'
import { useNavigate, useLocation } from "react-router-dom"
import axios from "../../utils/index"

export default function Password() {
    let location = useLocation()
    const { state } = location
    const user = JSON.parse(localStorage.getItem("user"))
    const navigate = useNavigate()
    const [visible, setVisible] = useState(false)
    const [val, setVal] = useState('')
    const [pwd, setPwd] = useState('1234')




    const onChange = (number) => {
        if (val.length <= 3) {
            setVal(prevValue => prevValue + number);
        }
    }
    const onDelete = () => {
        setVal(prevValue => prevValue.slice(0, -1));
    }

    const onSubmit = async (val) => {
        if (val === pwd) {
            await sleep(2000)
            let list = await axios.put("/price", { item: { id: user._id, price: state } })
            if (list.code === 200) {
                Toast.show({
                    content: '充值成功',
                    position: 'top',
                })
                let list = await axios.post("/water", { item: { name: "充值钱包", imgUrl: user.img, time: new Date(), price: state, text: "充值", uid: user._id } })
                if (list.code === 200) {
                    //随机生成优惠卷过期时间
                    let timeArr = [0, 2, 3, 6, 14, 29]
                    const randomIndex = Math.floor(Math.random() * timeArr.length);
                    const randomValue = timeArr[randomIndex];
                    const originalTime = new Date();
                    const date = new Date(originalTime);
                    date.setDate(date.getDate() + randomValue);
                    const year = date.getFullYear();
                    const month = (date.getMonth() + 1).toString().padStart(2, '0');
                    const day = date.getDate().toString().padStart(2, '0');
                    const hours = date.getHours().toString().padStart(2, '0');
                    const minutes = date.getMinutes().toString().padStart(2, '0');
                    const newTime = `${year}-${month}-${day}T${hours}:${minutes}:00.000+00:00`;
                    //随机生成优惠卷文本
                    let textArr = ["特别促销仅限于今天!", "最高抵扣15元", "胜券在握,百般实惠", "不讨价还价,有优惠卷"]
                    const randomIndex1 = Math.floor(Math.random() * textArr.length);
                    const randomValue1 = textArr[randomIndex1];
                    //随机折扣
                    let discountArr = [9, 8, 7, 6]
                    const randomIndex2 = Math.floor(Math.random() * discountArr.length);
                    const randomValue2 = discountArr[randomIndex2];

                    let lists = await axios.post("/addVou", { name: "网约车劵", time: newTime, uid: user._id, text: randomValue1, discount: randomValue2 })
                    console.log(lists);
                    if (lists.code === 200) {
                        navigate("/all/money")
                    }
                }

            }
        }
    };

    const subSmits = async () => {
        if (val.length <= 3) {
            Toast.show({
                content: '请输入完整密码',
                position: 'top',
            })
        } else {
            if (val === '1234') {
                let list = await axios.put("/price", { item: { id: user._id, price: state } })
                if (list.code === 200) {
                    Toast.show({
                        content: '充值成功',
                        position: 'top',
                    })
                    let list = await axios.post("/water", { item: { name: "充值钱包", imgUrl: user.img, time: new Date(), price: state, text: "充值", uid: user._id } })
                    if (list.code === 200) {
                        //随机生成优惠卷过期时间
                        let timeArr = [0, 2, 3, 6, 14, 29]
                        const randomIndex = Math.floor(Math.random() * timeArr.length);
                        const randomValue = timeArr[randomIndex];
                        const originalTime = new Date();
                        const date = new Date(originalTime);
                        date.setDate(date.getDate() + randomValue);
                        const year = date.getFullYear();
                        const month = (date.getMonth() + 1).toString().padStart(2, '0');
                        const day = date.getDate().toString().padStart(2, '0');
                        const hours = date.getHours().toString().padStart(2, '0');
                        const minutes = date.getMinutes().toString().padStart(2, '0');
                        const newTime = `${year}-${month}-${day}T${hours}:${minutes}:00.000+00:00`;
                        //随机生成优惠卷文本
                        let textArr = ["特别促销仅限于今天!", "最高抵扣15元", "胜券在握,百般实惠", "不讨价还价,有优惠卷"]
                        const randomIndex1 = Math.floor(Math.random() * textArr.length);
                        const randomValue1 = textArr[randomIndex1];
                        //随机折扣
                        let discountArr = [9, 8, 7, 6]
                        const randomIndex2 = Math.floor(Math.random() * discountArr.length);
                        const randomValue2 = discountArr[randomIndex2];

                        let lists = await axios.post("/addVou", { name: "网约车劵", time: newTime, uid: user._id, text: randomValue1, discount: randomValue2 })
                        if (lists.code === 200) {
                            navigate("/all/money")
                        }
                    }

                }
            } else {
                Toast.show({
                    content: '密码错误',
                    position: 'top',
                })
                setVal('')
            }
        }
    }

    return (
        <div className="body">
            <div className="top1">
                <div className="return1">
                    <span className="icon1">
                        <Space gap={20}>
                            <Down className="leftIcon1" onClick={() => { navigate("/recharge") }} />
                        </Space>
                    </span>
                    <span className="top-cart1">请输入你的PIN码</span>
                </div>
            </div>
            <div className="pass-text">请输入您的PIN码已确认充值</div>

            <PasswordInput length={4} onSubmit={onSubmit} value={val} onFocus={() => { setVisible(true) }} />

            <Button block color='primary' size='large' className='password-button' loading='auto' loadingText='正在加载' onClick={async () => {
                await sleep(2000)
                subSmits()
            }}>
                继续
            </Button>

            <NumberKeyboard
                visible={visible}
                type="rightColumn"
                custom={['.', 'x']}
                onChange={onChange}
                onDelete={onDelete}
                onClose={() => setVisible(false)}
                onConfirm={() => { setVisible(false) }}
            />
        </div>
    )
}
